<template>
  <PageWrapper dense contentFullHeight contentClass="flex">
    <div v-if="listConfig.isLeftMenu" class="w-1/5 xl:w-1/5 mr-2">
      <BasicTree
        :title="listConfig.leftMenuConfig?.menuName"
        toolbar
        search
        :clickRowToExpand="true"
        :treeData="treeData"
        :fieldNames="fieldNames"
        @select="handleSelect"
      >
        <template #title="item">
          <template v-if="item.renderIcon === 'parentIcon'">
            <Icon :icon="listConfig.leftMenuConfig?.parentIcon" />
          </template>
          <template v-if="item.renderIcon === 'childIcon'">
            <Icon :icon="listConfig.leftMenuConfig?.childIcon" />
          </template>
          {{ treeTitle(item) }}
        </template>
      </BasicTree>
    </div>

    <div :class="listConfig.isLeftMenu ? `w-4/5 xl:w-4/5` : `w-full`">
      <BasicTable @register="registerTable">
        <template #toolbar>
          <template v-for="button in tableButtonConfig" :key="button.code">
            <a-button v-if="button.isDefault" type="primary" @click="buttonClick(button.code)">
              <template #icon><Icon :icon="button.icon" /></template>
              {{ button.name }}
            </a-button>
            <a-button v-else type="primary">
              <template #icon><Icon :icon="button.icon" /></template>
              {{ button.name }}
            </a-button>
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.componentType === 'switch'">
            <a-switch
              v-model:checked="record[column.dataIndex]"
              :unCheckedValue="0"
              :checkedValue="1"
              :disabled="true"
            />
          </template>
          <template v-if="column.componentType === 'picker-color'">
            <ColorPicker v-model:value="record[column.dataIndex]" :disabled="true" />
          </template>
          <template v-if="column.componentType === 'money-chinese'">
            {{
              !isNaN(record[column.dataIndex]) && record[column.dataIndex] !== null
                ? nzhcn.encodeB(record[column.dataIndex]) + '元'
                : ''
            }}
          </template>
          <template v-if="column.dataIndex === 'action'">
            <TableAction :actions="getActions(record)" />
          </template>
        </template>
      </BasicTable>
    </div>

    <FormModal
      v-if="formType === 'modal'"
      @register="registerModal"
      @success="handleSuccess"
      :formType="formType"
      :formWidth="formWidth"
    />
    <FormModal
      v-else
      @register="registerDrawer"
      @success="handleSuccess"
      :formType="formType"
      :formWidth="formWidth"
    />
    <ImportModal
      @register="registerImportModal"
      importUrl="/form/execute/import"
      :data="{ releaseId: menuId }"
      @success="handleImportSuccess"
    />
    <LookProcess
      v-if="visibleLookProcessRef"
      :taskId="taskIdRef"
      :processId="processIdRef"
      @close="visibleLookProcessRef = false"
      :visible="visibleLookProcessRef"
    />
    <LaunchProcess
      v-if="visibleLaunchProcessRef"
      :schemaId="schemaIdRef"
      :form-data="formDataRef"
      :form-id="formIdComputedRef"
      @close="handleCloseLaunch"
    />
    <ApprovalProcess
      v-if="visibleApproveProcessRef"
      :taskId="taskIdRef"
      :processId="processIdRef"
      :schemaId="schemaIdRef"
      @close="handleCloseApproval"
      :visible="visibleApproveProcessRef"
    />
    <SetRuleUserModal @register="registerRuleUserModal" @success="handleRuleUserSuccess" />
    <PrintPreview
      v-if="visiblePrintPreview"
      :id="printData.id"
      :request-params-configs="printData.requestParamsConfigs"
      :request-body-configs="printData.requestBodyConfigs"
      :request-header-configs="printData.requestHeaderConfigs"
      @close="visiblePrintPreview = false"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import {
    BasicColumn,
    BasicTable,
    FormProps,
    FormSchema,
    TableAction,
    useTable,
    ActionItem,
  } from '/@/components/Table';
  import { useDrawer } from '/@/components/Drawer';
  import { PageWrapper } from '/@/components/Page';
  import FormModal from './components/FormModal.vue';
  import { ColorPicker } from '/@/components/ColorPicker';
  import { ImportModal } from '/@/components/Import';
  import SetRuleUserModal from '/@/components/Designer/src/components/generateComponent/SetRuleUserModal.vue';
  import Icon from '/@/components/Icon/index';
  import LookProcess from '/@/views/workflow/task/components/LookProcess.vue';
  import LaunchProcess from '/@/views/workflow/task/components/LaunchProcess.vue';
  import ApprovalProcess from '/@/views/workflow/task/components/ApprovalProcess.vue';
  import { downloadByData } from '/@/utils/file/download';
  import { onMounted, ref, unref, computed, createVNode, provide, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import { getFormTemplate } from '/@/api/form/design';
  import { getFormRelease } from '/@/api/form/release';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { FormReleaseConfig, GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { ColumnConfig, ListConfig, QueryConfig } from '/@/model/generator/listConfig';
  import { FormEventColumnConfig } from '/@/model/generator/formEventConfig';
  import { buildOption } from '/@/utils/helper/designHelper';
  import { whetherNeedToTransform, findSchema } from '/@/utils/helper/generatorHelper';
  import { ComponentOptionModel } from '/@/model/generator/codeGenerator';
  import {
    deleteFormExecute,
    getFormExecutePage,
    getFormExecuteWorkflow,
    exportForm,
    setDataAuth,
    getFormExecute,
  } from '/@/api/form/execute';
  import { handleSearchForm } from '/@/utils/helper/exportHelper';
  import { useTabs } from '/@/hooks/web/useTabs';
  import { useTitle } from '@vueuse/core';
  import { useGlobSetting } from '/@/hooks/setting';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { TreeItem, BasicTree } from '/@/components/Tree';
  import { getDicDetailList } from '/@/api/system/dic';
  import { apiConfigFunc, generateTableJson } from '/@/utils/event/design';
  import { Modal } from 'ant-design-vue';
  import { CloseCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import nzhcn from 'nzh/cn';
  import printJS from 'print-js';
  import { getPrintConfigInfo } from '/@/api/system/generator/print';
  import PrintPreview from '/@/views/generator/print/Preview.vue';
  import { PrintButton } from '/@/enums/printEnum';
  import { InputParamItem } from '/@/components/ApiConfig/src/interface';
  interface SearchDate {
    fieldName: string;
    format: string;
  }
  const { setTitle } = useTabs();
  const { title } = useGlobSetting();
  const { currentRoute } = useRouter();
  const { path } = unref(currentRoute);
  const printMenuId = computed(() => currentRoute.value.meta.menuId as string);
  const { filterColumnAuth, filterButtonAuth } = usePermission();

  let columns: BasicColumn[] = [], //列表配置
    searchFormSchema: FormSchema[] = [], //搜索框配置
    searchDate: SearchDate[] = [], //搜索栏时间组件配置
    formProps: FormProps = {}, //表单配置
    listConfig = ref<ListConfig>({
      isLeftMenu: false,
      isPage: false,
      queryConfigs: [],
      columnConfigs: [],
      buttonConfigs: [],
      listTitle: '',
    }), //列表配置
    formEventConfig = ref<FormEventColumnConfig>([]), //表单事件配置
    treeData = ref<any[]>([]), //树结构数据
    selectId = ref<string>(''), // 左侧菜单所选;
    formType = ref<string>(''), //弹窗类型：modal、drawer
    formWidth = ref<number>(800), // 弹窗、抽屉宽度
    menuId = ref<string>(''),
    pkField = ref<string>(''); //主表主键
  // 模板打印 入参参数
  let printData: {
    id: string;
    requestParamsConfigs: Array<InputParamItem>;
    requestHeaderConfigs: Array<InputParamItem>;
    requestBodyConfigs: Array<InputParamItem>;
  } = reactive({
    id: '',
    requestParamsConfigs: [],
    requestHeaderConfigs: [],
    requestBodyConfigs: [],
  });
  //展示在列表内的按钮
  const actionButtons = ref<string[]>(['view', 'edit', 'delete', 'startwork']);
  const { notification } = useMessage();
  const { t } = useI18n();
  defineEmits(['register']);
  const selectedKeys = ref<string[]>([]);
  const selectedRowsData = ref<any[]>([]);

  const isDataAuth = ref<boolean>(false);

  const listTitle = ref<string>('');
  const pageParamsInfo = ref<any>({});

  provide<boolean>('isCustomForm', true);
  const paths = path.split('/');
  menuId.value = paths.length > 0 ? paths[paths.length - 1] : '';
  const filterColumns = ref<BasicColumn[]>([]);
  const buttonConfigs = computed(() => {
    if (!listConfig.value.buttonConfigs) return;
    return filterButtonAuth(listConfig.value.buttonConfigs.filter((x) => x.isUse));
  });

  const tableButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => !actionButtons.value.includes(x.code));
  });

  const actionButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => actionButtons.value.includes(x.code));
  });

  const visibleLookProcessRef = ref(false);
  const processIdRef = ref('');

  const visibleLaunchProcessRef = ref(false);
  const schemaIdRef = ref('');
  const formDataRef = ref();

  const visibleApproveProcessRef = ref(false);
  const taskIdRef = ref('');

  const formIdComputedRef = ref('');

  const visiblePrintPreview = ref(false);
  const btnEvent = {
    refresh: handleRefresh,
    view: handleView,
    add: handleAdd,
    edit: handleEdit,
    delete: handleDelete,
    batchdelete: handleBatchdelete,
    batchSetUserId: handleBatchSetUserId,
    import: handleImport,
    export: handleExport,
    print: handlePrint,
  };

  const fieldNames = computed(() => {
    return {
      key: listConfig.value.leftMenuConfig?.datasourceType === 'static' ? 'key' : 'value',
      title:
        listConfig.value.leftMenuConfig?.datasourceType === 'dic'
          ? 'name'
          : listConfig.value.leftMenuConfig?.datasourceType === 'api'
          ? 'label'
          : listConfig.value.leftMenuConfig?.showFieldName || 'title',
    };
  });

  const treeTitle = (item) => {
    switch (listConfig.value.leftMenuConfig?.datasourceType) {
      case 'dic':
        return item.name;
      case 'api':
        return item.label;
      default:
        return item[listConfig.value.leftMenuConfig?.showFieldName || 'title'];
    }
  };
  const [registerModal, { openModal }] = useModal();
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerImportModal, { openModal: openImportModal }] = useModal();
  const [registerRuleUserModal, { openModal: openRuleUserModal }] = useModal();

  const [registerTable, { reload, setProps, setSelectedRowKeys, getRawDataSource }] = useTable({
    title: '',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
    },
    beforeFetch: (pageParams) => {
      //发送请求默认新增  左边树结构所选机构id
      const newParams = {
        releaseId: menuId.value,
        params: pageParams,
        order: pageParams.order,
        field: pageParams.field,
      };
      pageParamsInfo.value = {
        releaseId: menuId.value,
        params: pageParams,
      };
      //如果有左侧菜单 需要加上左侧树 所选项  作为参数
      if (listConfig.value.isLeftMenu) {
        newParams[listConfig.value.leftMenuConfig?.listFieldName as string] =
          pageParams[listConfig.value.leftMenuConfig?.listFieldName as string] || selectId.value;
      }
      newParams['headers'] = {
        FormId: formIdComputedRef.value,
        PK: pkField.value,
      };
      return newParams;
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 160,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    customRow,
  });

  function customRow(record: Recordable) {
    return {
      onClick: () => {
        let selectedRowKeys = [...selectedKeys.value];
        if (selectedRowKeys.indexOf(record[pkField.value]) >= 0) {
          let index = selectedRowKeys.indexOf(record[pkField.value]);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record[pkField.value]);
        }
        selectedKeys.value = selectedRowKeys;
        setSelectedRowKeys(selectedKeys.value);
      },
    };
  }
  function buttonClick(code) {
    if (code.includes(PrintButton.CODE)) {
      printTemplate(code);
    } else {
      btnEvent[code]();
    }
  }
  // 模板打印
  async function printTemplate(code) {
    if (!selectedKeys.value.length) {
      notification.warning({
        message: t('提示'),
        description: t('请选择数据'),
      });
      return;
    }
    if (selectedKeys.value.length > 1) {
      notification.warning({
        message: t('提示'),
        description: t('只能选择一条数据进行操作'),
      });
      return;
    }
    let id = selectedKeys.value[0];
    try {
      const record = await getFormExecute({ releaseId: menuId.value, id: id });
      let res = await getPrintConfigInfo(code, printMenuId.value);
      if (res.enabledMark == null) {
        notification.warning({
          message: t('提示'),
          description: t('当前功能未绑定打印模板，请绑定后再进行模板打印。'),
        });
        return;
      }
      if (res.enabledMark == 0) {
        notification.warning({
          message: t('提示'),
          description: t('找不到打印模板，请联系管理员。'),
        });
        return;
      }
      printData.id = res.schemaId;
      if (res.id && res.apiConfig) {
        let json = JSON.parse(res.apiConfig);
        if (json.requestParamsConfigs && json.requestParamsConfigs.length > 0) {
          printData.requestParamsConfigs = json.requestParamsConfigs.map((ele) => {
            if (ele.config && record[ele.config] != undefined) {
              ele.value = record[ele.config];
            }
            return ele;
          });
        }
        if (json.requestHeaderConfigs && json.requestHeaderConfigs.length > 0) {
          printData.requestHeaderConfigs = json.requestHeaderConfigs.map((ele) => {
            if (ele.config && record[ele.config] != undefined) {
              ele.value = record[ele.config];
            }
            return ele;
          });
        }
        if (json.requestBodyConfigs && json.requestBodyConfigs.length > 0) {
          printData.requestBodyConfigs = json.requestBodyConfigs.map((ele) => {
            if (ele.config && record[ele.config] != undefined) {
              ele.value = record[ele.config];
            }
            return ele;
          });
        }
        visiblePrintPreview.value = true;
      } else {
        notification.warning({
          message: t('提示'),
          description: t('当前功能未绑定打印模板，请绑定后再进行模板打印。'),
        });
      }
    } catch (error) {}
  }
  function onSelectChange(rowKeys: [], selectedRows) {
    selectedKeys.value = rowKeys;
    selectedRowsData.value = selectedRows;

    setSelectedRowKeys(selectedKeys.value);
  }

  function handleRefresh() {
    reload();
  }

  function handleAdd() {
    if (formType.value === 'modal') {
      openModal(true, {
        isUpdate: false,
        releaseId: menuId.value,
        pkField: pkField.value,
        formEventConfig,
        formProps,
      });
    } else {
      openDrawer(true, {
        isUpdate: false,
        releaseId: menuId.value,
        pkField: pkField.value,
        formEventConfig,
        formProps,
      });
    }
  }

  function handleEdit(record: Recordable) {
    if (formType.value === 'modal') {
      openModal(true, {
        id: record[pkField.value],
        releaseId: menuId.value,
        pkField: pkField.value,
        isUpdate: true,
        formEventConfig,
        formProps,
      });
    } else {
      openDrawer(true, {
        id: record[pkField.value],
        releaseId: menuId.value,
        pkField: pkField.value,
        isUpdate: true,
        formEventConfig,
        formProps,
      });
    }
  }

  function handleView(record: Recordable) {
    if (formType.value === 'modal') {
      openModal(true, {
        id: record[pkField.value],
        releaseId: menuId.value,
        pkField: pkField.value,
        isView: true,
        formEventConfig,
        formProps,
      });
    } else {
      openDrawer(true, {
        id: record[pkField.value],
        releaseId: menuId.value,
        pkField: pkField.value,
        isView: true,
        formEventConfig,
        formProps,
      });
    }
  }

  async function handleDelete(record: Recordable) {
    deleteList([record[pkField.value]]);
  }

  async function handlePrint() {
    const dataSource = Array.isArray(getRawDataSource())
      ? getRawDataSource()
      : getRawDataSource().list;
    const json = generateTableJson(filterColumns.value, dataSource);
    const properties = filterColumns.value.map((item) => item.title);
    printJS({
      printable: json,
      properties: properties,
      type: 'json',
    });
  }

  function handleBatchdelete() {
    if (!selectedKeys.value.length) {
      notification.warning({
        message: t('提示'),
        description: t('请选择需要删除的数据'),
      });
      return;
    }
    //与工作流相关的数据不能进行批量删除
    const cantDelete = selectedRowsData.value.filter((x) => {
      return (x.workflowData?.enabled && x.workflowData?.status) || !!x.workflowData?.processId;
    });
    if (cantDelete.length) {
      notification.warning({
        message: 'Tip',
        description: t('含有不能删除的数据'),
      });
      return;
    }
    deleteList(selectedKeys.value);
  }

  function deleteList(ids) {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否确认删除？'),
      okText: t('确认'),
      cancelText: t('取消'),
      onOk() {
        deleteFormExecute({ releaseId: menuId.value, ids }).then((_) => {
          reload();
          notification.success({
            message: t('提示'),
            description: t('删除成功！'),
          });
        });
      },
      onCancel() {},
    });
  }

  function handleBatchSetUserId() {
    if (!isDataAuth.value) {
      Modal.confirm({
        title: t('操作失败'),
        icon: createVNode(CloseCircleOutlined, { style: 'color: #ed6f6f' }),
        content: createVNode(
          'div',
          { style: 'color: #999' },
          t('当前功能未配置数据权限，请配置后再进行操作。'),
        ),
        centered: true,
        okText: t('确定'),
        cancelText: t('取消'),
        onOk() {},
        onCancel() {},
      });
      return;
    }
    if (!selectedKeys.value.length) {
      notification.warning({
        message: t('提示'),
        description: t('请选择需要设置权限的数据'),
      });
      return;
    }
    openRuleUserModal(true, {
      rowKey: pkField.value,
      columns: filterColumns.value,
      dataSource: selectedRowsData.value,
      setDataAuthApi: setDataAuth, //设置权限的接口地址
      params: { releaseId: menuId.value },
      isCustomForm: true,
    });
  }

  function handleRuleUserSuccess() {
    selectedKeys.value = [];
    selectedRowsData.value = [];
    setSelectedRowKeys([]);
    reload();
  }

  async function handleExport() {
    const fileName = listTitle.value;
    const res = await exportForm({ ...pageParamsInfo.value });
    downloadByData(
      res.data,
      `${fileName}.xlsx`,
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  }

  function handleImport() {
    openImportModal(true, {
      title: t('快速导入'),
      downLoadUrl: '/form/execute/export',
      type: 'POST',
    });
  }

  function handleImportSuccess() {
    reload();
  }

  function handleSuccess() {
    reload();
  }

  function handleViewWorkflow(record: Recordable) {
    if (record.workflowData) {
      visibleLookProcessRef.value = true;
      processIdRef.value = record.workflowData.processId;
    }
  }
  async function handleLaunchProcess(record: Recordable) {
    if (record.workflowData) {
      const result = await getFormExecuteWorkflow({
        formId: formIdComputedRef.value,
        id: record[pkField.value],
      });

      visibleLaunchProcessRef.value = true;
      schemaIdRef.value = record.workflowData.schemaId;
      formDataRef.value = result;
    }
  }
  function handleApproveProcess(record: Recordable) {
    visibleApproveProcessRef.value = true;
    schemaIdRef.value = record.workflowData.schemaId;
    processIdRef.value = record.workflowData.processId;
    taskIdRef.value = record.workflowData.taskIds[0];
  }
  function handleCloseLaunch() {
    visibleLaunchProcessRef.value = false;
    reload();
  }
  function handleCloseApproval() {
    visibleApproveProcessRef.value = false;
    reload();
  }

  onMounted(async () => {
    //获取发布数据
    const releaseResult = await getFormRelease(menuId.value as string);
    const configJson = JSON.parse(releaseResult.configJson) as FormReleaseConfig;
    formIdComputedRef.value = releaseResult.formId;
    //设置Tab标题
    setTitle(configJson.menuConfig.name);
    //设置浏览器标题
    useTitle(` ${configJson.menuConfig.name} - ${title} `);
    //设置是否需要左侧菜单
    listConfig.value = configJson.listConfig!;
    listTitle.value = listConfig.value.listTitle || configJson.menuConfig.name;
    const { queryConfigs, columnConfigs } = configJson.listConfig!;

    //如果设置了左侧菜单  需要请求菜单数据
    if (listConfig.value.isLeftMenu) {
      fetchLeftData();
    }
    //获取表单模板数据
    const templateResult = await getFormTemplate(releaseResult.formId);
    const formJson = JSON.parse(templateResult.formJson) as GeneratorConfig;
    isDataAuth.value = formJson.isDataAuth;

    const mainTable = formJson.tableConfigs?.find((item) => item.isMain);
    pkField.value = mainTable?.pkField || 'id';

    //构建表单Props
    formProps = buildOption(formJson.formJson, false);
    formType.value = formJson.formJson.config.formType!;
    formWidth.value = formJson.formJson.config.formWidth || 800;
    formEventConfig.value = formJson.formEventConfig;
    //查询配置转换为schema
    [searchFormSchema, searchDate] = ConvertQueryConfigToFormSchema(
      queryConfigs,
      formProps.schemas!,
      formJson.formJson.list,
    );
    //列表配置 转换为 BasicColumn
    columns = ConvertColumnConfigToBasicColumn(columnConfigs);
    filterColumns.value = filterColumnAuth(columns);
    const hasListCheckbox = tableButtonConfig.value?.some(
      (x) =>
        ['batchdelete', 'batchSetUserId'].includes(x.code) || x.code.includes(PrintButton.CODE),
    );
    //是否展示多选按钮
    if (hasListCheckbox) {
      setProps({
        rowSelection: {
          onChange: onSelectChange,
        },
      });
    }
    //重新设定table组件props
    setProps({
      api: getFormExecutePage,
      title: listTitle.value,
      rowKey: pkField.value,
      columns: filterColumns.value,
      formConfig: {
        labelWidth: 100,
        schemas: searchFormSchema,
        fieldMapToTime: searchDate.map((date) => {
          return [
            date.fieldName!,
            [date.fieldName + 'Start', date.fieldName + 'End'],
            date.format,
            true,
          ];
          // [['fieldTime', ['startTime', 'endTime'], 'YYYY-MM-DD']],
        }),
      },
    });
    reload();
  });

  function getActions(record: Recordable): ActionItem[] {
    const hasStartWorkButton = buttonConfigs.value?.some((x) => x.code === 'startwork');
    let actionsList: ActionItem[] = [];
    let editAndDelBtn: ActionItem[] = [];

    actionButtonConfig.value?.map((button) => {
      if (button.code === 'view') {
        actionsList.push({
          icon: button?.icon,
          tooltip: button?.name,
          onClick: handleView.bind(null, record),
        });
      }
      if (['edit', 'delete'].includes(button.code)) {
        editAndDelBtn.push({
          icon: button?.icon,
          tooltip: button?.name,
          color: button.code === 'delete' ? 'error' : undefined,
          onClick: btnEvent[button.code].bind(null, record),
        });
      }
    });
    if (record.workflowData?.enabled) {
      if (!hasStartWorkButton) return actionsList;
      //与工作流有关联的表单
      if (record.workflowData.status) {
        //如果是本人需要审批的数据 就会有taskIds  所以需要修改绑定事件
        const act: ActionItem = {};
        if (record.workflowData.taskIds) {
          act.tooltip = t('查看流程(待审批)');
          act.icon = 'daishenpi|svg';
          act.onClick = handleApproveProcess.bind(null, record);
        } else {
          act.tooltip =
            t('查看流程') +
            (record.workflowData.status === 'ACTIVE' ? t('(审批中)') : t('(已完成)'));
          act.icon =
            record.workflowData.status === 'ACTIVE' ? 'jinshenpi|svg' : 'shenpiwancheng|svg';
          act.onClick = handleViewWorkflow.bind(null, record);
        }
        actionsList.unshift(act);
      } else {
        actionsList.unshift({
          icon: 'faqishenpi|svg',
          tooltip: t('发起审批'),
          onClick: handleLaunchProcess.bind(null, record),
        });
        actionsList = actionsList.concat(editAndDelBtn);
      }
    } else {
      if (!record.workflowData?.processId) {
        //与工作流没有关联的表单并且在当前页面新增的数据 如选择编辑、删除按钮则加上
        actionsList =
          actionButtonConfig.value
            ?.filter((x) => x.code !== 'startwork')
            .map((button) => {
              return {
                icon: button?.icon,
                tooltip: button?.name,
                color: button.code === 'delete' ? 'error' : undefined,
                onClick: btnEvent[button.code].bind(null, record),
              };
            }) || [];
      }
    }
    return actionsList;
  }

  function handleSelect(selectIds) {
    selectId.value = selectIds[0];
    reload({
      searchInfo: { [listConfig.value.leftMenuConfig?.listFieldName as string]: selectId.value },
    });
  }

  async function fetchLeftData() {
    //如果是数据字典
    if (listConfig.value.leftMenuConfig?.datasourceType === 'dic') {
      treeData.value = (await getDicDetailList({
        itemId: listConfig.value.leftMenuConfig.dictionaryItemId,
      })) as unknown as TreeItem[];
    } else if (listConfig.value.leftMenuConfig?.datasourceType === 'static') {
      //如果是静态数据
      treeData.value = listConfig.value.leftMenuConfig.staticData!;
    } else if (listConfig.value.leftMenuConfig?.datasourceType === 'api') {
      //如果是api
      treeData.value = (await apiConfigFunc(
        listConfig.value.leftMenuConfig?.apiConfig,
        false,
      )) as unknown as TreeItem[];
    }
    addRenderIcon(treeData.value);
  }

  function addRenderIcon(data) {
    data.map((item) => {
      if (item.children?.length) addRenderIcon(item.children);
      return (item.renderIcon = item.children?.length ? 'parentIcon' : 'childIcon');
    });
  }

  /**
   * QueryConfig 转换 为搜索栏 FormSchema
   * 根据查询字段 获取到 当前字段查询组件的类型
   * 普通类型：input
   * 远程组件：ApiSelect
   * 时间字段：RangePicker
   */
  function ConvertQueryConfigToFormSchema(
    queryConfigs: QueryConfig[],
    schemas: FormSchema[],
    list: ComponentOptionModel[],
  ): [FormSchema[], SearchDate[]] {
    const searchDate: SearchDate[] = [];
    const searchFormSchema = queryConfigs.map((config) => {
      if (!!config.isDate) {
        searchDate.push({
          fieldName: config.fieldName,
          format: config.format!,
        });
      }
      const schema = findSchema(schemas, config.fieldName);
      const [isNeedTrans, option] = whetherNeedToTransform(config, list);

      return handleSearchForm(option, schema, config, isNeedTrans, false) as FormSchema;
    });
    return [searchFormSchema, searchDate];
  }

  /**
   *
   * columnConfig转 BasicColumn
   * @param columnConfigs
   */
  function ConvertColumnConfigToBasicColumn(columnConfigs: ColumnConfig[]): BasicColumn[] {
    return columnConfigs.map((config) => {
      const column: BasicColumn = {
        dataIndex: config.columnName,
        title: config.label,
        componentType: config.componentType,
        sorter: true,
      };
      if (config.alignType) column.align = config.alignType as any;
      if (config.isTotal) column.total = true;
      if (!config.autoWidth && config.columnWidth) column.width = config.columnWidth;
      if (config.componentProps?.datasourceType === 'staticData') {
        column.customRender = ({ record }) => {
          const staticOptions = config.componentProps?.staticOptions;
          return staticOptions.filter((x) => x.value === record[config.columnName])[0]?.label;
        };
      }
      return column;
    });
  }
</script>
<style lang="less" scoped>
  :deep(.ant-table-selection-col) {
    width: 50px;
  }
</style>
